function setCookie(key, value, timing) {
    var date = new Date();
    date.setDate(date.getDate() + timing);
    document.cookie = key + "=" + value + ";expires=" + date;
}
function getCookie(key) {
    var arr = document.cookie.split("; ");
    for (var i = 0; i < arr.length; i++) {
        var arr2 = arr[i].split("=");
        if (key === arr2[0]) {
            return arr2[1]
        }
    }
}
function removeCookie(key) {
    setCookie(key, "", -1);
}
var goods = document.querySelector(".total-goods");
var allChecked = document.querySelector('.quanxuan');
var arr = getCookie("carts") ? JSON.parse(getCookie("carts")) : [];
// 总价格
var total = 0;
fillTbody();
// 计算总价格
calc_total();
function fillTbody() {
    var str = "";
    for (var i = 0; i < arr.length; i++){
        var tr = `
                <div class="carts-goods">
				    <div class="sub_content fl ">
					    <input type="checkbox" data-index='${i}' ${arr[i].isChecked ? 'checked' : ''}  class="xuanze" />
				    </div>
				    <div class="sub_content fl"><img src="../images/mi10.jpg"></div>
				    <div class="sub_content fl">${ arr[i].itemName}</div>
				    <div class="sub_content fl">${ arr[i].itemPrice} </div>
				    <div class="sub_content fl">
					    <button class="num">${ arr[i].itemNum}</button>
					    <button  data-index='${i}' class="btn" id="jia">+</button>
					    <button  data-index='${i}' class="btn" id="jian">-</button>
				    </div>
				    <div class="sub_content fl">${ (arr[i].itemPrice * arr[i].itemNum).toFixed(2)}</div>
				    <div class="sub_content fl"><span data-index='${i}' class="del">删除</span></div>
				    <div class="clear"></div>
			    </div>	
                `
        // 创建行
        str += tr;
    }
    goods.innerHTML = str;
    var add = document.querySelectorAll('#jia'); //增加按钮
    var reduce = document.querySelectorAll("#jian"); //减少按钮
    var del = document.querySelectorAll('.del'); //删除按钮
    var checkes = document.querySelectorAll('.xuanze'); //商品选中按钮
    for (var i = 0; i < add.length; i++) {
        //商品添加数量
        add[i].onclick = function () {
            var index = parseInt(this.dataset.index);
            arr[index].itemNum++;
            fillTbody();
            // 计算总价格
            calc_total();
        }
        //商品减少数量
        reduce[i].onclick = function () {
            var index = parseInt(this.dataset.index);
            arr[index].itemNum--;
            if (arr[index].itemNum <= 1) {
                arr[index].itemNum = 1;
            }
            fillTbody();
            // 计算总价格
            calc_total();
        }
        //删除的功能
        del[i].onclick = function () {
            var index = parseInt(this.dataset.index);
            // 数组 怎么删除 元素  
            if (confirm("您确认删除吗")) {
                arr.splice(index, 1);
                fillTbody();
                calc_total();
                setCookie("carts",JSON.stringify(arr),5)
            }
        }
        //商品选中 取消选中
        checkes[i].onchange = function () {
            var index = parseInt(this.dataset.index);
            var checked = this.checked;
            var allChecked = document.querySelector('.quanxuan');
            arr[index].isChecked = checked;
            //判断 是不是所有的商品都被选中了，只要有没有被选中的全选取消，反之全选勾选
            var bool = arr.every(function (el) {
                return el.isChecked;
            })
            if (!bool) {
                // 有一个没选中 取消全选
                allChecked.checked = false;
            } else {
                //全部选中  勾选全选
                allChecked.checked = true;
            }
            fillTbody();
            calc_total();
        }
    }
    setCookie("carts",JSON.stringify(arr),5)
}
//点击全选和取消全选
allChecked.onchange = function(){
    if( this.checked ){
        arr.forEach(function(el){
            el.isChecked = true;
        })
    }else{
        arr.forEach(function(el){
            el.isChecked = false;
        })
    }
    fillTbody();
    calc_total();
}
// 计算总价格的函数
function calc_total() {
    total = 0; 
    var totalEl = document.querySelector('.total-price');
    var subArr = arr.filter(function (el) {
        return el.isChecked;
    });
    subArr.forEach(function (el) {
        total += el.itemPrice * el.itemNum
    })
    total = parseFloat(total.toFixed(2));
    totalEl.innerHTML = total;
}
